// JavaScript Document



$j(function(){
    window.document.title = Static.appName;
    $j("#ribbon").ribbon();

    //Load default data image
    (function(){
        new Ajax.Request("test/MyImageDefault.json", {
            method: 'get',
            onSuccess: function (transport) {
                try {
                    Global.myImageDefaultSpec = transport.responseText.evalJSON(true);
                }
                catch (err){
                    console.log(err);
                }
            },
            onFailure: function () {
                alert("JSON Fail");
            }
        });
    })();
    //Load default data text
    (function(){
        new Ajax.Request("test/MyTextDefault.json", {
            method: 'get',
            onSuccess: function (transport) {
                try {
                    Global.myTextDefaultSpec = transport.responseText.evalJSON(true);
                }
                catch (err){
                    console.log(err);
                }
            },
            onFailure: function () {
                alert("JSON Fail");
            }
        });
    })();
    //Load default data video
    (function(){
        new Ajax.Request("test/MyVideoDefault.json", {
            method: 'get',
            onSuccess: function (transport) {
                try {
                    Global.myVideoDefaultSpec = transport.responseText.evalJSON(true);
                }
                catch (err){
                    console.log(err);
                }
            },
            onFailure: function () {
                alert("JSON Fail");
            }
        });
    })();
    //Load default data audio
    (function(){
        new Ajax.Request("test/MyAudioDefault.json", {
            method: 'get',
            onSuccess: function (transport) {
                try {
                    Global.myAudioDefaultSpec = transport.responseText.evalJSON(true);
                }
                catch (err){
                    console.log(err);
                }
            },
            onFailure: function () {
                alert("JSON Fail");
            }
        });
    })();

    //init Menu
    initFileMenu();
    initToolsMenu();
    initEditMenu();
    //init right column
    initRightColumn();
    initSetting();
    Global.propertyEditor = new PropertyEditor(Static.containerPropertyEditor);
    Global.elementsView = new ElementsView(Static.containerElementsView);
    Global.elementClipboard = new ElementClipboard();

    Global.undoRedo = new UndoRedo();
});

function initFileMenu(){
    //File-->New Book
    (function(){
        var OK = function(){
            //Get name from input for new book
            var name = $j("#" + Static.dialogNewBook + " input").val();
            //Check if name is blank string
            if(name != ""){
                Global.currentBook = new MyBook({
                    name: name
                });
                window.document.title += " - " + name;
                //Done: Close dialog
                $j("#" + Static.dialogNewBook).dialog("close");
            }

        };

        $j("#" + Static.dialogNewBook).dialog({
            autoOpen: false,
            modal: true,
            buttons: {
                "Ok": OK,
                "Cancel": function(){
                    $j("#" + Static.dialogNewBook).dialog("close");
                }
            },
            show: true,
            hide: true,
            resizable: false
        });

        $j("#" + Static.btnNewBook).on("click", function(event){
            //Hien tai dang co book
            if(Global.currentBook !== null){
                //Show confirm  dialog
                $j("#" + Static.dialogConfirmNewBook).dialog({
                    autoOpen: true,
                    modal: true,
                    buttons: {
                        "Yes": function(){
                            //Xoa book hien tai
                            Global.currentBook.destroy();
                            Global.elementClipboard.clear();
                            Global.undoRedo.clear();
                            //Xoa title App
                            window.document.title = Static.appName;

                            $j("#" + Static.dialogConfirmNewBook).dialog("destroy");
                            $j("#" + Static.dialogNewBook).dialog("open");
                        },
                        "No": function(){
                            $j("#" + Static.dialogConfirmNewBook).dialog("destroy");
                        }
                    },
                    show: true,
                    hide: true,
                    resizable: false
                });
            }
            //Neu khong co thi khoi tao moi hoan toan
            else{
                $j("#" + Static.dialogNewBook).dialog("open");
            }

        });
    })();

    //File-->Save
    $j("#" + Static.btnSave).on("click", function(){
        if(Global.currentBook != null){

            $j("#" + Static.dialogConfirmSave).dialog({
                autoOpen: true,
                modal: true,
                show: true,
                hide: true,
                resizable: false,
                buttons: {
                    "Yes": function(){
                        MyTools.saveLocally('book', $j.toJSON(Global.currentBook.toJSON()));
                        $j("#" + Static.dialogConfirmSave).dialog("destroy");
                    },
                    "No": function(){
                        $j("#" + Static.dialogConfirmSave).dialog("destroy");
                    }
                }
            });
        }
    });

    //File-->Open
    $j("#" + Static.btnOpen).on("click", function(){
        if(Global.currentBook != null){
            //Show confirm  dialog
            $j("#" + Static.dialogConfirmOpenBook).dialog({
                autoOpen: true,
                modal: true,
                buttons: {
                    "Yes": function(){
                        //Xoa book hien tai
                        Global.currentBook.destroy();
                        Global.elementClipboard.clear();
                        Global.undoRedo.clear();
                        Global.currentBook = new MyBook({
                            name: ""
                        });
                        var data = MyTools.loadLocally('book');
                        Global.currentBook.fromJSON($j.evalJSON(data));
                        $j("#" + Static.dialogConfirmOpenBook).dialog("destroy");
                    },
                    "No": function(){
                        $j("#" + Static.dialogConfirmOpenBook).dialog("destroy");
                    }
                },
                show: true,
                hide: true,
                resizable: false
            });
        }
        else {
            Global.currentBook = new MyBook({
                name: ""
            });
            var data = MyTools.loadLocally('book');
            Global.currentBook.fromJSON($j.evalJSON(data));
        }

    });

    //File-->Export
    $j("#" + Static.btnExport).on("click", function(){
        if(Global.currentBook != null){

            $j("#" + Static.dialogConfirmExport).dialog({
                autoOpen: true,
                modal: true,
                show: true,
                hide: true,
                resizable: false,
                buttons: {
                    "Yes": function(){
                        var exporter = new MyExporter();
                        var jsonObject = exporter.export(Global.currentBook, function(){
                            $j("#" + Static.dialogConfirmExport).dialog("destroy");
                        });
                    },
                    "No": function(){
                        $j("#" + Static.dialogConfirmExport).dialog("destroy");
                    }
                }
            });


        }
    });

    //File-->Insert Before
    $j("#" + Static.btnInsertBefore).on("click", function(){
        if(Global.currentBook != null && Global.currentPage != null){
            Global.currentBook.createNewPage("before");
        }
    });

    //File-->Insert After
    $j("#" + Static.btnInsertAfter).on("click", function(){
        if(Global.currentBook != null && Global.currentPage != null){
            Global.currentBook.createNewPage("after");
        }
    });

    //File-->Delete Page
    $j("#" + Static.btnDeletePage).on("click", function(){
        if(Global.currentBook != null && Global.currentPage != null){
            $j("#" + Static.dialogConfirmDeletePage).dialog({
                autoOpen: true,
                modal: true,
                show: true,
                hide: true,
                resizable: false,
                buttons: {
                    "Yes": function(){

                        $j("#" + Static.dialogConfirmDeletePage).dialog("destroy");
                        Global.currentBook.removePageById(Global.currentPage.id);
                    },
                    "No": function(){
                        $j("#" + Static.dialogConfirmDeletePage).dialog("destroy");
                    }
                }
            });
        }
    });

};
function initToolsMenu(){
    $j("#" + Static.btnImage).on("click", function(event){
        //Kiem tra xem co page nao dang active ko ?
        if(Global.currentBook != null && Global.currentPage != null){
            //Khoi tao mot doi tuong Image moi
            var newImage = new MyImage({parent: Global.currentPage});
            newImage.initAttributeList(Global.myImageDefaultSpec);
            Global.currentPage.addElement(newImage);
            newImage.initEvents();
            //Them doi tuong image vao trong trang hien tai

        }
    });


    $j("#" + Static.btnText).on("click", function(event){
        //Kiem tra xem co page nao dang active ko ?
        if(Global.currentBook != null && Global.currentPage != null){
            var newText = new MyText({parent: Global.currentPage});
            newText.initAttributeList(Global.myTextDefaultSpec);
            Global.currentPage.addElement(newText);
            newText.initEvents();
        }

    });

    $j("#" + Static.btnVideo).on("click", function(event){
        //Kiem tra xem co page nao dang active ko ?
        if(Global.currentBook != null && Global.currentPage != null){
            var newVideo = new MyVideo({parent: Global.currentPage});
            newVideo.initAttributeList(Global.myVideoDefaultSpec);
            Global.currentPage.addElement(newVideo);
            newVideo.initEvents();
        }

    });

    $j("#" + Static.btnAudio).on("click", function(event){
        //Kiem tra xem co page nao dang active ko ?
        if(Global.currentBook != null && Global.currentPage != null){
            var newAudio = new MyAudio({parent: Global.currentPage});
            newAudio.initAttributeList(Global.myAudioDefaultSpec);
            Global.currentPage.addElement(newAudio);
            newAudio.initEvents();
        }

    });
};
function initEditMenu(){
    $j("#" + Static.btnCopyElement).on("click", function(){
        if(Global.currentPage != null && Global.currentSelectedEle != null){
            var ele = Global.currentPage.getElementById(Global.currentSelectedEle);
            Global.elementClipboard.copy(ele);
        }
    });

    $j("#" + Static.btnCutElement).on("click", function(){
        if(Global.currentPage != null && Global.currentSelectedEle != null){

            var ele = Global.currentPage.getElementById(Global.currentSelectedEle);
            Global.elementClipboard.cut(ele);

            Global.propertyEditor.clear();
        }
    });

    $j("#" + Static.btnPasteElement).on("click", function(){
        if(Global.currentPage != null){
            Global.elementClipboard.paste(Global.currentPage);
        }
    });

    $j("#"+Static.btnDelete).on("click", function(){
        if(Global.currentSelectedEle != null){
            Global.currentPage.removeElementById(Global.currentSelectedEle);
            Global.currentSelectedEle = null;
            Global.propertyEditor.clear();
        }
    });

    $j("#" + Static.btnUndo).on("click", function(){
        if(Global.currentBook != null){
            var undoData = Global.undoRedo.popUndoStack();

            if(undoData != null){
                if(undoData.action == "ADD_PAGE" || undoData.action == "REMOVE_PAGE"){
                    if(undoData.action == "ADD_PAGE"){
                        Global.undoRedo.pushRedoStack("ADD_PAGE", Global.currentBook.toJSON());
                    }
                    if(undoData.action == "REMOVE_PAGE"){
                        Global.undoRedo.pushRedoStack("REMOVE_PAGE", Global.currentBook.toJSON());
                    }

                    if(Global.currentBook != null){
                        Global.currentBook.destroy();
                    };
                    Global.currentBook = new MyBook({
                        name: ""
                    });

                    Global.currentBook.fromJSON(undoData.data);

                    Global.currentPage = null;
                    Global.currentSelectedEle = null;
                    //Clear PropertyEditor
                    Global.propertyEditor.clear();

                    //Clear ElementsView
                    Global.elementsView.clear();
                }
                else if(undoData.action == "ADD_ELEMENT" || undoData.action == "REMOVE_ELEMENT"){
                    var page = Global.currentBook.getPageById(undoData.data.id);

                    if(undoData.action == "ADD_ELEMENT"){
                        Global.undoRedo.pushRedoStack("ADD_ELEMENT", page.toJSON());
                    }
                    if(undoData.action == "REMOVE_ELEMENT"){
                        Global.undoRedo.pushRedoStack("REMOVE_ELEMENT", page.toJSON());
                    }

                    page.fromJSON(undoData.data);

                    if(Global.currentSelectedEle != null){
                        $j("#" + Global.currentSelectedEle).removeClass("resource-selected");

                    }
                    Global.currentSelectedEle = null;

                    page.setActive(true);
                    MyTools.viewThumbnail(page.id);
                }
                else if(undoData.action == "ELEMENT_PROPERTY"){
                    var id = undoData.data.id;
                    var page = Global.currentBook.getPageById(undoData.data.pageId);
                    var ele = page.getElementById(id);

                    Global.undoRedo.pushRedoStack("ELEMENT_PROPERTY", ele.toJSON());
                    ele.reloadAttributeList(undoData.data);

                    page.setActive(true);
                    MyTools.viewThumbnail(page.id);
                    if(Global.currentSelectedEle == id){
                        Global.propertyEditor.load(ele);

                    }
                }
            }
        }
    });

    $j("#" + Static.btnRedo).on("click", function(){
        var redoData = Global.undoRedo.popRedoStack();

        if(redoData != null){
            if(redoData.action == "ADD_PAGE" || redoData.action == "REMOVE_PAGE"){
                if(redoData.action == "ADD_PAGE"){
                    Global.undoRedo.pushUndoStack("ADD_PAGE", Global.currentBook.toJSON(), true);
                }
                if(redoData.action == "REMOVE_PAGE"){
                    Global.undoRedo.pushUndoStack("REMOVE_PAGE", Global.currentBook.toJSON(), true);
                }

                if(Global.currentBook != null){
                    Global.currentBook.destroy();
                };

                Global.currentBook = new MyBook({
                    name: ""
                });

                Global.currentBook.fromJSON(redoData.data);

                Global.currentPage = null;
                Global.currentSelectedEle = null;
                //Clear PropertyEditor
                Global.propertyEditor.clear();

                //Clear ElementsView
                Global.elementsView.clear();
            }
            else if(redoData.action == "ADD_ELEMENT" || redoData.action == "REMOVE_ELEMENT"){
                var page = Global.currentBook.getPageById(redoData.data.id);

                if(redoData.action == "ADD_ELEMENT"){
                    Global.undoRedo.pushUndoStack("ADD_ELEMENT", page.toJSON(), true);
                }
                if(redoData.action == "REMOVE_ELEMENT"){
                    Global.undoRedo.pushUndoStack("REMOVE_ELEMENT", page.toJSON(), true);
                }

                page.fromJSON(redoData.data);

                if(Global.currentSelectedEle != null){
                    $j("#" + Global.currentSelectedEle).removeClass("resource-selected");

                }
                Global.currentSelectedEle = null;

                page.setActive(true);
                MyTools.viewThumbnail(page.id);
            }
            else if(redoData.action == "ELEMENT_PROPERTY"){
                var id = redoData.data.id;
                var page = Global.currentBook.getPageById(redoData.data.pageId);
                var ele = page.getElementById(id);

                Global.undoRedo.pushUndoStack("ELEMENT_PROPERTY", ele.toJSON(), true);
                ele.reloadAttributeList(redoData.data);

                if(Global.currentSelectedEle == id){
                    Global.propertyEditor.load(ele);

                }

                page.setActive(true);
                MyTools.viewThumbnail(page.id);
            }
        }
    });
};
function initRightColumn(){
    $j("#tab-properties").on("click", function(){
        if(!$j(this).hasClass("sel")){
            $j("#" + Static.rightColumn).find(".tab-header-strip .tab-header.sel").removeClass("sel");
            $j(this).addClass("sel");
            $j(".tab-section").css("display", "none");
            $j("#" + Static.containerPropertyEditor).css("display", "block");
        }
    });

    $j("#tab-elements").on("click", function(){
        if(!$j(this).hasClass("sel")){
            $j("#" + Static.rightColumn).find(".tab-header-strip .tab-header.sel").removeClass("sel");
            $j(this).addClass("sel");
            $j(".tab-section").css("display", "none");
            $j("#" + Static.containerElementsView).css("display", "block");
        }
    });
};

function initSetting(){
    $j(".ribbon-tab-header:last-child").on("click", function(){
        if(Global.currentBook == null){
            $j("#"+Static.settingView).css("display", "none");
        }
        else{
            $j("#"+Static.settingView).css("display", "block");
            $j("#" + Static.settingView).find("tr.setting-preview img").attr("src", Global.currentBook.coverImage);
            $j("#" + Static.settingView).find("tr.setting-book-name input").val(Global.currentBook.name);
            //Target Device here
        }
    });

    $j("#" + Static.settingView).find("tr.setting-preview button").on("click", function(){
        if(Global.currentBook != null){
            var img = $j("#" + Static.settingView).find("tr.setting-preview img");

            $j("#" + Static.dialogImageChooser).dialog({
                autoOpen: true,
                width: 500,
                modal: true,
                position: [300,100]
            });

            $j.getJSON("getImagesList.php", function(data){

                $j("#"+Static.dialogImageChooser).empty();
                $j.each(data, function(index, value){
                    var finalDelimiter = value.lastIndexOf("/");
                    var firstStr = value.substring(0, finalDelimiter+1);
                    var fileName = value.substring(finalDelimiter+1)
                    var thumbPath = firstStr + "thumbnail/" + fileName;

                    $j("<img/>").attr("src", thumbPath).attr("filePath", value).attr("title", fileName).attr("alt", fileName)
                        .appendTo("#"+Static.dialogImageChooser).addClass("image-chooser").on("click", function(){
                            $j(img).attr('src', value);
                            Global.currentBook.coverImage = value;
                            $j("#" + Static.dialogImageChooser).dialog("close");
                        });
                });
            });
        }
    });

    $j("#" + Static.settingView).find("tr.setting-book-name input").keyup(function(e){
        if(Global.currentBook != null){
            if(e.keyCode == 13){
                Global.currentBook.name = this.value;
                this.blur();
            }
        }
    });
};